import json

import random

from django.http import JsonResponse
from django_redis import get_redis_connection

from verifications import forms
from users.models import User
from utils.captcha.captcha import captcha
from django.http import HttpResponse
from django.views import View
import logging

from utils.json_fun import to_json_data
from utils.res_code import Code, error_map
from utils.yuntongxun.sms import CCP
from celery_tasks.sms import task as sms_tasks


logger = logging.getLogger('django')
# class ImageCode(View):
#     def get(self, request,image_code_id):
#         text, image = captcha.generate_captcha()
#         return HttpResponse(content=image, content_type='image/jpg')

class ImageCode(View):

    def get(self, request,image_code_id):
        text, image = captcha.generate_captcha()
        conn_redis = get_redis_connection('verify_codes')
        conn_redis.setex('img_{}'.format(image_code_id),300,text)
        logger.info('Image code: {}'.format(text))
        return HttpResponse(content=image, content_type='image/jpg')


class CheckUsernameView(View):
    """
    username / （？p<username>\w{5,20})/
    """


    def get(self, request, username):
        # count = User.objects.get(username=username).count
        data = {
            'username': username,
            'count': User.objects.filter(username=username).count()
        }
        return JsonResponse({'data':data})


class CheckMobileView(View):
    """
    GET mobiles/(?P<mobile>1[3-9]\d{9})/
    """

    def get(self, request,mobile):
        # 先获取用户名的数量
        count =  User.objects.filter(mobile=mobile).count()
        data = {
            'mobile':mobile,
            'count': count
        }
        return to_json_data(data=data)


class SmsCodesView(View):

    """
1，获取参数
2，验证参数
3，发送短信
4，保存短信验证码
5，返回给前端
    send mobile sms code
    POST /sms_codes/
- 检查图片验证码是否正确
- 检查是否在60s内有发送记录
- 生成短信验证码
- 保存短信验证码与发送记录
- 发送短信

    """
    # 1, 获取参数
    def post(self,request):
        json_str = request.body        # json数据  mobile    text   image_code_id
        if not json_str:
            return to_json_data(errno=Code.PARAMERR,errmsg='参数为空，请重新输入')
        # 将json数据转为字典
        dict_data = json.loads(json_str.decode('utf8'))
        # print(dict_data)
        # dict_data = dict(dict_data)

    # 2，校验参数   新建form表单认证  [手机号，验证码 ]
        # 引入云通讯文件  注册好
        form = forms.CheckImgCodeForm(data=dict_data)

        if form.is_valid():
            # 获取手机号

            # 从表单里面获取mobile
            mobile = form.cleaned_data.get('mobile')

            # 创建短信验证码内容   在常量文件里面添加内容
            # 列表生成式拼接
            sms_num = "%06d" % random.randint(0, 999999)
            # 将短信验证码保存到数据库
            # 确保settings.py文件中有配置redis CACHE
            # Redis原生指令参考 http://redisdoc.com/index.html
            # Redis python客户端 方法参考 http://redis-py.readthedocs.io/en/latest/#indices-and-tables
            # 4、
            con_redis = get_redis_connection(alias='verify_codes')
            # 创建一个在60s以内是否有发送短信记录的标记
            sms_flag_fmt = "sms_flag_{}".format(mobile).encode('utf8')    # 记号为1
            # 创建保存短信验证码的标记key
            sms_text_fmt = "sms_{}".format(mobile).encode('utf8')
            # con_redis.setex(sms_flag_fmt, constants.SEND_SMS_CODE_INTERVAL, 1)
            # con_redis.setex(sms_text_fmt, constants.SMS_CODE_REDIS_EXPIRES, sms_num)

            pl = con_redis.pipeline()
            # 此处设置为True会出现bug
            try:
                pl.setex(sms_flag_fmt, 60, 1)
                pl.setex(sms_text_fmt, 300, sms_num)
                # 让管道通知redis执行命令
                pl.execute()
            except Exception as e:
                logger.debug("redis 执行出现异常：{}".format(e))
                return to_json_data(errno=Code.UNKOWNERR, errmsg=error_map[Code.UNKOWNERR])

            # 获取到短信验证码信息输出到日志
            logger.info("Sms code: {}".format(sms_num))
            # # # 发送短信验证码

            # 发送短信
            # logging.info('Sms Code : {}'.format(sms_num))
            # return to_json_data(errno=Code.OK,errmsg='短信验证码发送成功')
            # expires = 300
            # sms_tasks.send_sms_code.delay(mobile,sms_num,expires,1)
            # return to_json_data(errno=Code.OK, errmsg='短信验证码发送成功')
            expires = 300
            sms_tasks.send_sms_code.delay(mobile, sms_num, expires, 1)
            return to_json_data(errno=Code.OK, errmsg="短信验证码发送成功")

            # try:
            #     result = CCP().send_template_sms(mobile,
            #                                  [sms_num, 5], 1)  # 1
            # except Exception as e:
            #     logger.error("发送验证码短信[异常][ mobile: %s, message: %s ]" % (mobile, e))
            #     return to_json_data(errno=Code.SMSERROR, errmsg=error_map[Code.SMSERROR])
            # else:
            #     if result == 0:
            #         logger.info("发送验证码短信[正常][ mobile: %s sms_code: %s]" % (mobile, sms_num))
            #         return to_json_data(errno=Code.OK, errmsg='短信验证码发送成功')
            #     else:
            #         logger.warning("发送验证码短信[失败][ mobile: %s ]" % mobile)
            #         return to_json_data(errno=Code.SMSFAIL, errmsg=error_map[Code.SMSFAIL])

        else:
            # 定义错误信息列表
            err_msg_list = []
            for item in form.errors.get_json_data().values():
                err_msg_list.append(item[0].get('message'))
            err_msg_str = '/'.join(err_msg_list)
            return to_json_data(errno=Code.PARAMERR,errmsg=err_msg_str)




